//
//  SingWithoutMusicViewCtr.m
//  CCBbelefitLife
//
//  Created by liurg on 16/1/2.
//  Copyright © 2016年 liurg. All rights reserved.
//

#import "SingWithoutMusicViewCtr.h"
#import <AudioToolbox/AudioToolbox.h>
#import "lame.h"
#import "Utilities.h"
#import "CustomPickerBottomView.h"
#import "SingRecordFinshView.h"



#define  TempRecordPath  @"tempRecordPath"
#define  TempRecordName  @"tempQingChangName.caf"
#define  DocRecordPath  @"docRecordPath"

//#define  TempRecordPath  @"tempRecordPath"
//#define  TempRecordName  @"tempQingChangName"
//#define  DocRecordPath  @"docRecordPath"
//#define  DocRecordName  @"docQingChangName"


@interface SingWithoutMusicViewCtr ()<CustomPickerBottomViewDelegate>

{
    BOOL isOrigin;
    BOOL isPopular;
    BOOL isRock;
    NSInteger seleEq;
    UISlider * _soundSlider;
    NSMutableArray * seleArray;
}
@property(nonatomic,assign) BOOL isRecording;
@property(nonatomic,assign) CGFloat sampleRate;
@property(nonatomic,assign) AVAudioQuality quality;
@property(nonatomic,assign) NSInteger formatIndex;
@property(nonatomic,retain) NSString *recordedFile;
@property(nonatomic,retain) AVAudioRecorder *recorderAudio;
@property(nonatomic,retain) NSTimer *recTimer;
@property(nonatomic,retain) UILabel *recordDesLab;
@property(nonatomic,retain) NSString *recordedFileName;
@property(nonatomic,retain) NSString *mp3FileName;
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) UIButton *recordMaiBtn;

@end

@implementation SingWithoutMusicViewCtr

- (void)viewDidLoad {
    [super viewDidLoad];
    
    isOrigin = YES;
    isPopular = NO;
    isRock = NO;
    seleEq = 0;
    seleArray = [[NSMutableArray alloc]initWithCapacity:10];
    
    
#warning 停止外围播放音频  隐藏返回按钮
    [[DOUAudioEventLoop sharedEventLoop] stop];
    
    [self configData];
    [self setupView];
    [self buildNavView];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self recordSingMusic:_recordMaiBtn];
//    });

    
}

- ( void ) viewWillAppear:( BOOL ) animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    self.tabBarController.tabBar.hidden = YES;
    // [ShareAppDelegate.ApptabBar hideSysTabar];
}


-(void)buildNavView{
    
    self.title = @"清唱";
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"" highIcon:@"" target:self action:nil];
    
}

-(void)backBtnAction{
    [_recorderAudio stop];
    [[NSFileManager defaultManager] removeItemAtPath:_recordedFileName error:nil];
    [self.navigationController popViewControllerAnimated:YES];
    //  [[UIApplication sharedApplication] setStatusBarHidden:NO];
}


-(void)configData{
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    _sampleRate  = 44100.0;
    _quality     = AVAudioQualityLow;
    if(session == nil)
        NSLog(@"Error creating session: %@", [sessionError description]);
    else
        [session setActive:YES error:nil];
    
    _sampleRate = 44100.0;
    _formatIndex=kAudioFormatLinearPCM;
    _quality     =  AVAudioQualityHigh;
}

-(void)setupView{
    
    UIImageView *backViewImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth, mainScreenHeight-64)];
    backViewImg.image = [UIImage imageNamed:@"清唱背景"];
    [self.view addSubview:backViewImg];
    UIButton *MVModelBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 15, 80, 28)];
    MVModelBtn.backgroundColor = JYColor(238, 237, 240);
    [self.view addSubview:MVModelBtn];
    [MVModelBtn setTitle:@"MV模式" forState:UIControlStateNormal];
    [MVModelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    MVModelBtn.layer.cornerRadius = 14;
    
    UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(MVModelBtn.righX+8, MVModelBtn.y+MVModelBtn.height/2-2, 4, 4)];
    redView.backgroundColor = [UIColor redColor];
    redView.layer.cornerRadius = 2.0;
    [self.view addSubview:redView];
    self.recordDesLab = [[UILabel alloc]initWithFrame:CGRectMake(MVModelBtn.righX+20, 15, 180, 28)];
    self.recordDesLab.text = @"正在录制 00:00 / 00:00";
    self.recordDesLab.textColor = [UIColor whiteColor];
    self.recordDesLab.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.recordDesLab];
    _recordDesLab = self.recordDesLab;
    
    UIButton *recordMaiBtn = [[UIButton alloc]initWithFrame:CGRectMake(80, 80, mainScreenWidth-80*2, mainScreenWidth-80*2)];
    [self.view addSubview:recordMaiBtn];
    [recordMaiBtn setBackgroundImage:[UIImage imageNamed:@"mai"] forState:UIControlStateNormal];
    [recordMaiBtn addTarget:self action:@selector(recordSingMusic:) forControlEvents:UIControlEventTouchUpInside];
    _recordMaiBtn = recordMaiBtn;
    
    //构建底部栏    //构建底部栏
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, mainScreenHeight-50-64, mainScreenWidth, 50)];
    bottomView.backgroundColor = JYColor(238, 239, 241);
    [self.view addSubview:bottomView];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0, 10, 1, 30)];
    lineView.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:lineView];
    
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0*2, 10, 1, 30)];
    lineView1.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:lineView1];
    
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:leftBtn];
    [leftBtn addTarget:self action:@selector(saveLeftBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *flowerImg = [[UIImageView alloc]initWithFrame:CGRectMake((leftBtn.width-20)/2, 15, 20, 20)];
    flowerImg.image = [UIImage imageNamed:@"qc_flower"];
    [leftBtn addSubview:flowerImg];
    
    UIButton *middleBtn = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:middleBtn];
    [middleBtn addTarget:self action:@selector(finishDecod) forControlEvents:UIControlEventTouchUpInside];
    UILabel *desLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 15, middleBtn.width, 20)];
    desLab.textAlignment = NSTextAlignmentCenter;
    desLab.text = @"保存录音";
    [middleBtn addSubview:desLab];
    
//    _soundSlider = [[UISlider alloc]initWithFrame:CGRectMake(mainScreenWidth-100 , mainScreenHeight-50-60, 100, 10)];
//    _soundSlider.hidden = YES;
//    [_soundSlider setThumbImage:[UIImage imageNamed:@"soundSlider.png"] forState:UIControlStateNormal];
//    [_soundSlider setThumbImage:[UIImage imageNamed:@"soundSlider.png"] forState:UIControlStateHighlighted];
//    [_soundSlider addTarget:self action:@selector(adjustVolume) forControlEvents:(UIControlEventValueChanged)];
//    _soundSlider.minimumValue = 0;
//    _soundSlider.maximumValue = 1;
//    [self.view addSubview:_soundSlider];
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0*2, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:rightBtn];
//    [rightBtn addTarget:self action:@selector(ringingBellBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *bellImg = [[UIImageView alloc]initWithFrame:CGRectMake((rightBtn.width-20)/2, 15, 20, 20)];
    bellImg.image = [UIImage imageNamed:@"ringingBell"];
    [rightBtn addSubview:bellImg];
    
}

-(void)saveLeftBtnAction{
    
    NSArray *titleArr = @[@"完成",@"重录",@"退出",@"取消"];
    CustomPickerBottomView *pickerBottomView = [[CustomPickerBottomView alloc]initWithFrame:CGRectMake(0, mainScreenHeight-50-60*titleArr.count, mainScreenWidth, 60*titleArr.count) titleArr:titleArr];
    pickerBottomView.delegate = self;
    
}

- (void)encodeMp3{
    if (!_isRecording)
    {
        [NSThread detachNewThreadSelector:@selector(convertToMp3) toTarget:self withObject:nil];
    }
}

//切换音频
-(void)cutMusicSize:(UIControl *)sender{
    if(sender.tag%3 == 0){
        isOrigin = YES;
        isPopular = NO;
        isRock = NO;
    }else if (sender.tag%3 == 1){
        isOrigin = NO;
        isPopular = YES;
        isRock = NO;
    }else if (sender.tag%3 == 2){
        isOrigin = NO;
        isPopular = NO;
        isRock = YES;
    }
    seleEq = sender.tag;
    for(int i = 0;i< seleArray.count;i++){
        
        if(i == sender.tag){
            ((UIImageView *)seleArray[i]).hidden = NO;
        }else{
            ((UIImageView *)seleArray[i]).hidden = YES;
        }
    }
}

//-(void)ringingBellBtnAction{
//    _soundSlider.hidden = !_soundSlider.hidden;
//}

- (void) convertToMp3
{
    // NSURL *recordedFileNameUrl = [NSURL fileURLWithPath:recordedFileName];
    @try {
        int read, write;
        
        FILE *pcm = fopen([_recordedFileName cStringUsingEncoding:1], "rb");  //source
        if(pcm == NULL){
            return;
        }
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([_mp3FileName cStringUsingEncoding:1], "wb");  //output
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, _sampleRate);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
        [self performSelectorOnMainThread:@selector(convertMp3Finish)
                               withObject:nil
                            waitUntilDone:YES];
    }
}

- (void) convertMp3Finish
{
    NSLog(@"sucess convert mp3");
}


//点击按钮录音
-(void)recordSingMusic:(UIButton *)recBtn{
    
    if (!_isRecording&&!_recTimer)
    {
        NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat: _sampleRate],                  AVSampleRateKey,
                                  [NSNumber numberWithInt: _formatIndex],                   AVFormatIDKey,
                                  [NSNumber numberWithInt: 2],                              AVNumberOfChannelsKey,
                                  [NSNumber numberWithInt: _quality],                       AVEncoderAudioQualityKey,
                                  nil];
        
        NSString *recordedFileName = [Utilities getTempSaveFilePathString: TempRecordName  filePath:TempRecordPath];
        _recordedFileName = recordedFileName;
        NSURL *recordedFileNameUrl = [NSURL fileURLWithPath:recordedFileName];
        NSError* error;
        _recorderAudio = [[AVAudioRecorder alloc] initWithURL:recordedFileNameUrl settings:settings error:&error];
        NSLog(@"%@", [error description]);
        if (error)
        {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Sorry"
                                                            message:@"your device doesn't support your setting"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles: nil];
            [alert show];
            return;
        }
        _isRecording = YES;
        [_recorderAudio prepareToRecord];
        _recorderAudio.meteringEnabled = YES;
        [_recorderAudio record];
        _recTimer = [NSTimer scheduledTimerWithTimeInterval:.01f
                                                     target:self
                                                   selector:@selector(timerUpdate)
                                                   userInfo:nil
                                                    repeats:YES];

    }
    else
    {
        if (recBtn.selected) {
            [_recTimer setFireDate:[NSDate distantFuture]];
            recBtn.selected = !(recBtn.selected);
        }
        else{
            [_recTimer setFireDate:[NSDate distantPast]];
        }
    }
}

- (void) timerUpdate
{
    if (_isRecording)
    {
        int m = _recorderAudio.currentTime / 60;
        int s = ((int) _recorderAudio.currentTime) % 60;
        //int ss = (_recorderAudio.currentTime - ((int) _recorderAudio.currentTime)) * 100;
        _recordDesLab.text = [NSString stringWithFormat:@"正在录制 %.2d:%.2d / 15:00", m, s];
        NSInteger fileSize =  [self getFileSize:_recordedFileName];
    }
}

- (NSInteger) getFileSize:(NSString*) path
{
    NSFileManager * filemanager = [[NSFileManager alloc]init] ;
    if([filemanager fileExistsAtPath:path]){
        NSDictionary * attributes = [filemanager attributesOfItemAtPath:path error:nil];
        NSNumber *theFileSize;
        if ( (theFileSize = [attributes objectForKey:NSFileSize]) )
            return  [theFileSize intValue];
        else
            return -1;
    }
    else
    {
        return -1;
    }
}



#pragma mark CustomPickerBottomViewDelegate

-(void)CustomPickerBottomSelect:(UIButton *)pickerBtn{
    
    NSInteger tag = pickerBtn.tag - 100;
    
    if(!_isRecording){
        return;
    }
    _isRecording = NO;
    [_recTimer invalidate];
    _recTimer = nil;
    
    if (_recorderAudio != nil )
    {
        [_recorderAudio stop];
        _recorderAudio = nil;
    }
    
    if (tag == 0)
    {
        EQPlayer * player = [[EQPlayer alloc] init];
        SingRecordFinshView *singRecViewCtr = [[SingRecordFinshView alloc]initWithPlayer:player];
        singRecViewCtr.eqcount = seleEq;
        singRecViewCtr.recordMusicPath = _recordedFileName;
        [self.navigationController pushViewController:singRecViewCtr animated:YES];
    }
    else if (tag == 1)
    {
        [_recorderAudio stop];
        [[NSFileManager defaultManager] removeItemAtPath:_recordedFileName error:nil];
        self.recordDesLab.text = @"正在录制 00:00 / 15:00";
        [self recordSingMusic:nil];
    }
    else if (tag == 2)
    {
        [_recorderAudio stop];
        [[NSFileManager defaultManager] removeItemAtPath:_recordedFileName error:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    }

}

- (void)finishDecod{
    if(!_isRecording){
        return;
    }
    _isRecording = NO;
    [_recTimer invalidate];
    _recTimer = nil;
    
    if (_recorderAudio != nil )
    {
        [_recorderAudio stop];
        _recorderAudio = nil;
    }
    EQPlayer * player = [[EQPlayer alloc] init];
    SingRecordFinshView *singRecViewCtr = [[SingRecordFinshView alloc]initWithPlayer:player];
    singRecViewCtr.eqcount = seleEq;
    singRecViewCtr.recordMusicPath = _recordedFileName;
    [self.navigationController pushViewController:singRecViewCtr animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
